﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.IO;
using System.Messaging;
using System.Timers;

namespace CDistributed.WindowsService
{
    public partial class ProcessMSMQ : ServiceBase
    {
        private const string queuePath = @".\private$\processMSMQ";
        private static MessageQueue queues;

        public ProcessMSMQ()
        {
            InitializeComponent();

            if (!MessageQueue.Exists(queuePath))
                MessageQueue.Create(queuePath);
            if (queues == null)
                queues = new MessageQueue(queuePath);
        }

        protected override void OnStart(string[] args)
        {
            ProcessMSMQ.AppendText(DateTime.Now + "：processMSMQ服务启动...");
            this.ReceiveMessage();
        }

        protected override void OnStop()
        {
            ProcessMSMQ.AppendText(DateTime.Now + "：processMSMQ服务停止.");
        }

        #region 辅助方法

        private void ReceiveMessage()
        {
            queues.ReceiveCompleted += new ReceiveCompletedEventHandler(ReceiveMessageCompleted);
            queues.BeginReceive();
        }

        //异步接收消息
        private void ReceiveMessageCompleted(object sender, ReceiveCompletedEventArgs e)
        {
            Message message = queues.EndReceive(e.AsyncResult);
            message.Formatter = new XmlMessageFormatter(new Type[] { typeof(string) });
            ProcessMSMQ.AppendText(DateTime.Now + "接收到消息：" + message.Body);

            queues.BeginReceive();
        }

        private static void AppendText(string content)
        {
            string fileName = DateTime.Now.ToString("yyyyMMdd") + ".log";
            string path = @"E:\source code\Test Project\CDistributed\CDistributed.Web\App_Data\MsmqLog\";
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string fullFilePath = path + fileName;
            content += System.Environment.NewLine;
            File.AppendAllText(fullFilePath, content);
        }

        #endregion
    }
}
